import React, { useEffect, useState } from 'react';
import Item from './item';
import storage from '../../../../utils/storage';
import { cloneDeep } from 'lodash';

let id = 0;

const ReceiveUser = (props) => {
  const { value, form } = props;
  const [data, setData] = useState([]);
  useEffect(() => {
    if (value && value.length) {
      setData(getInitData(value));
    } else {
      // 默认取当前用户
      const { name: label, mobile: phone, email, id: key } = storage.userInfo;
      const defaultData = {
        phone,
        email,
        user_id: { key, label },
        id,
      };
      setData([defaultData]);
    }
  }, [value]);

  const getInitData = (value) =>
    value.map((item) => {
      const { user_id: key, name: label } = item;
      return { ...item, id: id++, user_id: { key, label } };
    });

  const add = () => {
    const tempData = cloneDeep(data);
    tempData.push({
      user_id: '',
      phone: '',
      email: '',
      id: ++id,
    });
    setData(tempData);
  };

  const onDel = (index) => {
    const tempData = cloneDeep(data);
    tempData.splice(index, 1);
    setData(tempData);
  };

  const onNameChange = (user_id, nameOptions, index, id) => {
    const { key } = user_id;
    const targetObj = nameOptions.find((item) => item.user_id === key);
    const { user_mobile: phone, user_email: email } = targetObj;
    const tempData = cloneDeep(data);
    const tempUser = { user_id, phone, email, wx_work: undefined };
    tempData[index] = {
      ...tempData[index],
      ...tempUser,
    };
    // 更新form data
    const users = form.getFieldValue('users');
    users[id] = tempUser;
    form.setFieldsValue({ users });
    setData(tempData);
  };
  return (
    <>
      {data.map((item, index) => (
        <Item
          {...props}
          key={item.id}
          value={item}
          isAddShow={index === data.length - 1}
          isDelBtn={data.length !== 1}
          onAdd={add}
          onDel={() => onDel(index)}
          onNameChange={(user_id, nameOptions) => onNameChange(user_id, nameOptions, index, item.id)}
        />
      ))}
    </>
  );
};

export default ReceiveUser;
